package com.shuke.sk_worm.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.shuke.sk_worm.consts.ShopPlatformEnum;
import com.shuke.sk_worm.domain.SkAccounts;
import com.shuke.sk_worm.service.SkAccountsService;
import com.shuke.sk_worm.service.SkShopInfoService;
import com.shuke.sk_worm.tool.Worm;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("account")
public class ShopAccountController {

    @Autowired
    private SkShopInfoService shopInfoService;

    @Autowired
    private SkAccountsService accountsService;

    //重试次数
    private Integer retry = 4;

    private static final Logger logger =  Logger.getLogger(ShopAccountController.class);

    public void findShop(Long date){
        List<SkAccounts> accounts = shopInfoService.findShopAccounts(ShopPlatformEnum.DOUYIN);
        if (accounts == null){
            logger.info("未获取到抖音店铺账号");
            return;
        }

        for(SkAccounts vo : accounts){
            vo.setCreateTime(date);
        }

        //数据存入
        if (!accountsService.saveBatch(accounts)){
            logger.info("存入数据失败");
            return;
        }

        Worm worm = new Worm();
        worm.multiSaveShop(accounts, date);
        System.out.print("执行.............");

        //执行失败的从新执行
        Integer trys = 0;
        List<SkAccounts> retryAccount;
        do{
            retryAccount = accountsService.findFailAccounts(ShopPlatformEnum.DOUYIN, date);
            if (ObjectUtil.isNotEmpty(retryAccount)){
                worm.multiSaveShop(retryAccount, date);
            }
            trys++;
        }while (trys <= retry && ObjectUtil.isNotEmpty(retryAccount));
    }

    //@GetMapping("shop")
    public void cronShop(@Param(value = "time") Long date){
        //当天时间
        Date time = DateUtil.beginOfDay(DateUtil.date());
        Long now =  time.getTime();

        findShop(now);
    }

    @GetMapping("shop")
    public void postShop(@Param(value = "time") String time){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(time);
            long timestamp = date.getTime();
            findShop(timestamp);
        }catch (Exception e){

        }
    }
}
